package interceptor

import (
	"net/http"
	"time"

	"github.com/xinliangnote/go-gin-api/configs"
	"github.com/xinliangnote/go-gin-api/internal/code"
	"github.com/xinliangnote/go-gin-api/internal/pkg/core"
	"github.com/xinliangnote/go-gin-api/pkg/jwt"
	"github.com/xinliangnote/go-gin-api/internal/proposal"
	"github.com/xinliangnote/go-gin-api/pkg/errors"
)

func (i *interceptor) CheckLoginByJwt(ctx core.Context) (sessionUserInfo proposal.SessionUserInfo, err core.BusinessError) {
	token := ctx.GetHeader(configs.HeaderLoginToken)
	if token == "" {
		err = core.Error(
			http.StatusUnauthorized,
			code.AuthorizationError,
			code.Text(code.AuthorizationError)).WithError(errors.New("Header 中缺少 Token 参数"))

		return
	}
	secretkey := configs.Get().Jwt.SecretKey;
	jwt_st := jwt.NewMiniJwt(secretkey)
	parse_err := jwt_st.ParseToken(token)
	if parse_err!= nil {
		err = core.Error(
			http.StatusUnauthorized,
			code.AuthorizationError,
			code.Text(code.AuthorizationError)).WithError(parse_err)

		return
	}
	data, ok := jwt_st.(*jwt.JwtSt)
	if !ok {
		err = core.Error(
			http.StatusUnauthorized,
			code.AuthorizationError,
			code.Text(code.AuthorizationError)).WithError(errors.New("json web token parse 失败"))

		return
	}
	// 如果当前时间已经超过过期时间
	if time.Now().After(data.RegisteredClaims.ExpiresAt.Time) {
		err = core.Error(
			http.StatusUnauthorized,
			code.AuthorizationError,
			code.Text(code.AuthorizationError)).WithError(errors.New("token已经过期"))
		return
	} 
	sessionUserInfo.UserID = int32(data.UserID)
	sessionUserInfo.UserName = data.PhoneNumber
	return 
}
